package com.microservice.skeleton.upms.constraints;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @author: lijin
 * @date: 2018年11月07日
 */
public class SnippetTranslationResolver {

    private static ResourceBundle defaultMessages = getBundle("DefaultSnippetMessages");

    private static ResourceBundle userMessages = getBundle("SnippetMessages");

    private static ResourceBundle getBundle(String name) {
        try {
            return ResourceBundle.getBundle(
                    SnippetTranslationResolver.class.getPackage()
                            .getName() + "." + name,
                    Locale.getDefault(), Thread.currentThread().getContextClassLoader());
        } catch (MissingResourceException ex) {
            return null;
        }
    }

    public static String translate(String key, Object... args) {
        try {
            if (userMessages != null) {
                return format(userMessages.getString(key), args);
            }
        } catch (MissingResourceException ex) {
            // Continue and return default description, if available
        }
        return format(defaultMessages.getString(key), args);
    }

    // visible for testing
    static void setUserMessages(String name) {
        userMessages = getBundle(name);
    }

    private static String format(String message, Object[] args) {
        return new MessageFormat(message).format(args);
    }
}
